package com.tutorial.throttling.smoothbursty;

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.TimeUnit;

/**
 * Smoonth Bursty (平滑突发限流) And Smooth Warming Up (预热型平滑突发限流) With Guava
 *
 * Created by zhengqiang.sun on 2018/1/29.
 */
public class SmoothBurstyLearn {

    /**
     * 平滑突发限流
     */
    public void smoothBurstyThrottling() {
        Integer permitsPerSecond = 5;//每秒请求数量
        RateLimiter rateLimiter = RateLimiter.create(permitsPerSecond);
        System.out.println(rateLimiter.tryAcquire());
        System.out.println(rateLimiter.acquire(5));
        for (int i = 0; i < 10; i++) {
            System.out.println(rateLimiter.acquire());
        }
        System.out.println(rateLimiter.tryAcquire());
    }

    /**
     * 平滑突发限流（预热）
     */
    public void smoothWarmingUp() {
        Integer permitsPerSecond = 5;
        Integer warmupPeriod = 3;
        RateLimiter limiter = RateLimiter.create(permitsPerSecond, warmupPeriod, TimeUnit.SECONDS);
        for (int i = 0; i < 20; i++) {
            System.out.println(limiter.acquire());
        }
    }

    public static void main(String[] args) {
        SmoothBurstyLearn smoothBurstyLearn = new SmoothBurstyLearn();
        smoothBurstyLearn.smoothBurstyThrottling();
        smoothBurstyLearn.smoothWarmingUp();
    }
}
